package com.gitee.candy.string;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;

public class CustomerIPUtil {

    /**
     * 获取客户端ip
     */
    public static String getCustomerIP(HttpServletRequest request) {
        String userip = request.getHeader("forwarded"); //格式 Forwarded: for=192.0.2.43,for=[2001:db8:cafe::17],for=unknown
        try {
            if (userip != null && userip.length() != 0 && !"unknown".equalsIgnoreCase(userip)) {
                if (userip.indexOf(",") > 0) { // 如果有多个ip，则取第一个ip
                    String userips[] = userip.split(",");
                    for (int i = 0; i < userips.length; i++) {
                        if (userips[i].split("=")[0].equals("for") && userips[i].split("=")[1].indexOf(".") > 0) {//判断ip格式
                            userip = userips[i].split("=")[1];
                            break;
                        }
                    }
                } else {
                    if (userip.split("=")[0].equals("for") && userip.split("=")[1].indexOf(".") > 0) {//判断ip格式
                        userip = userip.split("=")[1];
                    } else {
                        userip = null;
                    }
                }
            }
            //查询代理
            if (userip == null || userip.length() == 0 || "unknown".equalsIgnoreCase(userip)) {
                String userip_x = request.getHeader("x-forwarded-for"); //格式X-Forwarded-For: client1, proxy1, proxy2
                if (userip_x != null && userip_x.length() != 0 && !"unknown".equalsIgnoreCase(userip_x)) {
                    if (userip_x.indexOf(",") > 0 || userip_x.indexOf(";") > 0) {
                        //暂时去掉下面的方式
                        //userip = request.getHeader("Client-IP");
                        String userips[] = null;
                        if (userip_x.indexOf(",") > 0) {//如果有多个
                            userips = userip_x.split(",");
                        } else if (userip_x.indexOf(";") > 0) {
                            userips = userip_x.split(";");
                        }
                        for (int i = 0; i < userips.length; i++) {
                            if ((userip == null || userip.length() == 0 || "unknown".equalsIgnoreCase(userip)) &&
                                    userips[i].indexOf(".") > 0) {//判断ip格式
                                userip = userips[i];
                                break;
                            }
                        }
                    } else {
                        userip = userip_x;
                    }
                }
            }
            if (userip == null || userip.length() == 0 || "unknown".equalsIgnoreCase(userip)) {
                userip = request.getHeader("Client-IP");
            }
            if (userip == null || userip.length() == 0 || "unknown".equalsIgnoreCase(userip)) {
                userip = request.getHeader("Proxy-Client-IP");
            }
            if (userip == null || userip.length() == 0 || "unknown".equalsIgnoreCase(userip)) {
                userip = request.getHeader("WL-Proxy-Client-IP");
            }
            if (userip == null || userip.length() == 0 || "unknown".equalsIgnoreCase(userip)) {
                userip = request.getRemoteAddr();
            }
            //如果代理IP是局域网IP
            if (userip != null && userip.length() > 4 && (
                    userip.substring(0, 2).equals("0.") ||
                            userip.substring(0, 3).equals("10.") ||
                            userip.substring(0, 4).equals("127.") ||
                            userip.substring(0, 4).equals("192.") ||
                            userip.substring(0, 4).equals("172.")
            )) {
                userip = request.getRemoteAddr();
            }
            //如果代理IP是局域网IP
			/*if (userip != null && userip.length() > 4 && (
					userip.substring(0, 2).equals("0.") ||
					userip.substring(0, 3).equals("10.") ||
					userip.substring(0, 4).equals("127.") ||
					userip.substring(0, 4).equals("192.") ||
					userip.substring(0, 4).equals("172.")
			)) {
				//如果从代理中没有找到有效的ip，最后查request.getRemoteAddr()，有可能还是局域网ip
				//因为有可能客户端使用了Apache,Squid等反向代理软件
				userip = "114.114.114.114";
			}*/
            if (userip == null || userip.length() < 5) {
                userip = "114.114.114.114";
                StringBuilder builder = new StringBuilder();
                builder.append("userip is null !")
                        .append("\n\t\treferer -> ").append(request.getHeader("Referer"))
                        .append("\n\t\trequsetURI -> ").append(request.getRequestURI())
                        .append("\n\t\tqueryString -> ").append(request.getQueryString())
                        .append("\n\t\tuserName -> ").append(request.getSession().getAttribute("will_session_userName"))
                        .append("\n\t\tsid -> ");
//                        .append(CookieMng.getCookie(request, "sid"));
            }
        } catch (Exception e) {
            userip = "127.0.0.1";
            StringBuilder builder = new StringBuilder();
            builder.append("getCustomerIP方法空指针异常！")
                    .append("\n\t\treferer -> ").append(request.getHeader("Referer"))
                    .append("\n\t\trequsetURI -> ").append(request.getRequestURI())
                    .append("\n\t\tqueryString -> ").append(request.getQueryString())
                    .append("\n\t\tforwarded -> ").append(request.getHeader("forwarded"))
                    .append("\n\t\tx-forwarded-for -> ").append(request.getHeader("x-forwarded-for"))
                    .append("\n\t\tClient-IP -> ").append(request.getHeader("Client-IP"))
                    .append("\n\t\tProxy-Client-IP -> ").append(request.getHeader("Proxy-Client-IP"))
                    .append("\n\t\tWL-Proxy-Client-IP -> ").append(request.getHeader("WL-Proxy-Client-IP"))
                    .append("\n\t\tgetRemoteAddr -> ").append(request.getRemoteAddr());
        }
        return userip;
    }

    public static String getServerIP() {
        String serverIP = "";
        Enumeration<NetworkInterface> netInterfaces = null;
        try {
            netInterfaces = NetworkInterface.getNetworkInterfaces();
            while (netInterfaces.hasMoreElements()) {
                NetworkInterface ni = netInterfaces.nextElement();
                Enumeration<InetAddress> ips = ni.getInetAddresses();
                while (ips.hasMoreElements()) {
                    InetAddress ip = ips.nextElement();
                    if (!ip.isLoopbackAddress()
                            && ip.getHostAddress().indexOf(":") == -1) {
                        serverIP = ip.getHostAddress();
                        break;
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return serverIP;
    }
}
